package com.store.orm.mysql.crud.impl;

import com.store.orm.mysql.MySQLUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 宫静雨
 * @version 1.0
 */
public class GroupSelect {
    private static final Logger logger = LoggerFactory.getLogger(GroupSelect.class);

    private MySQLUtil UTIL;

    public GroupSelect(MySQLUtil UTIL) {
        this.UTIL = UTIL;
    }

    public Map<String, List<Object>> group(String sql, Object... args) {
        Connection connection = UTIL.getConnection();
        Map<String, List<Object>> map = new LinkedHashMap<>();
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            ResultSet resultSet = ps.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            while (resultSet.next()) {
                for (int i = 0; i < columnCount; i++) {
                    String key = metaData.getColumnLabel(i + 1);
                    Object val = resultSet.getObject(i + 1);
                    if (!map.containsKey(key)) {
                        List<Object> list = new ArrayList<>();
                        list.add(val);
                        map.put(key, list);
                    } else {
                        List<Object> list = map.get(key);
                        list.add(val);
                        map.put(key, list);
                    }
                }
            }
            return map;
        } catch (SQLException e) {
            logger.error("分组查询时发生错误: {}", e.getMessage());
        }
        return null;
    }
}